package com.bea.ftd.dashboard.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bea.ftd.common.ValidationException;
import com.bea.ftd.common.dao.MsgMappingRepo;
import com.bea.ftd.common.entity.MsgMapping;
import com.bea.ftd.common.enums.ValidationErrorCode;
import com.bea.ftd.dashboard.service.IGatewayService;
import com.bea.ftd.dashboard.service.IMsgMappingService;
import com.bea.ftd.dashboard.validator.BooleanValidator;
import com.bea.ftd.dashboard.validator.NumberValidator;

@Service
public class MsgMappingServiceImpl implements IMsgMappingService, IGatewayService {
	private Logger LOGGER = LoggerFactory.getLogger(MsgMappingServiceImpl.class);

	@Autowired
	private BooleanValidator booleanValidator;
	@Autowired
	private NumberValidator numberValidator;
	
	@Autowired
	private MsgMappingRepo msgMappingRepo;

	@Override
	public void addMsgMapping(MsgMapping msgMapping) throws ValidationException {
		validateInputParams(msgMapping);
		setCreateOrUpdateTime(msgMapping, msgMappingRepo);
		msgMappingRepo.save(msgMapping);
	}

	/**
	 * 验证输入参数是否有效
	 * 
	 * @param msgMapping
	 * @throws ValidationException
	 */
	private void validateInputParams(MsgMapping msgMapping) throws ValidationException {

		if (!numberValidator.isNonNegtiveNumber(msgMapping.getInMsgId())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "输入报文id必须为大于等于0的值");
		}
		
		if (!numberValidator.isNonNegtiveNumber(msgMapping.getOutMsgId())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "输出报文id必须为大于等于0的值");
		}
		
		if (!booleanValidator.isBooleanType(msgMapping.getIsActivated())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "无效的isActivated值");
		}
	}
	
	@Override
	public List<MsgMapping> getAllMsgMappings() {
		try {
			return msgMappingRepo.findAll();
		} catch (Exception e) {
			LOGGER.error("error when querying msgMapping from database " + e.getMessage());
			return null;
		}
	}
}
